
#include <BFont>
#include <BScrollArea>

#include "member_BListWidget.h"
#include "member_BListItem.h"

using namespace BWE;

member_BListWidget::member_BListWidget(BListWidget* listWidget)
{
	boss = listWidget;
	spacing = 3;
	selectMode = Select_Multiple | Select_Contiguous;
	showItemBegin = -1;
	showItemEnd = -1;
	pressedItem = 0;
	hoveredItem = 0;
	dirty = false;
}
member_BListWidget::~member_BListWidget()
{

}

void member_BListWidget::freshArea()
{
	if (!dirty)
		return;

	const BFont* font = boss->font();
	if (!font)
		return;

	boss->verticalScrollBar()->setStep(font->size());

	int width = 0;
	int height = 0;
	for (int i = 0; i < items.size(); i++)
	{
		BListItem* item = items[i].ptr();
		item_member(item)->index = i;
		if (!item_member(item)->visible)
			continue;
		if (item_member(item)->dirty)
		{
			item_member(item)->freshSize(font);
			item_member(item)->dirty = false;
		}
		BSize& hintSize = item_member(item)->hintSize;
		width = bMax(hintSize.width(), width);
		height += spacing + hintSize.height();
	}
	minAreaSize.set(width, height);
	BRect area = boss->area();
	area.setSize(width, height);
	boss->setArea(area);

	{
		BRect area = boss->area();
		int width = area.width();
		int x = 0;
		int y = 0;
		for (int i = 0; i < items.size(); i++)
		{
			BListItem* item = items[i].ptr();
			if (!item_member(item)->visible)
				continue;
			int height = item_member(item)->hintSize.height();
			item_member(item)->adjustRect(x, y, width, height);
			y += spacing + height;
		}
	}
	dirty = false;
}
void member_BListWidget::freshVisualItems()
{
	BRect area = boss->area();
	BRect crect = boss->centerRect();
	int top = crect.top();
	int bottom = crect.bottom();
	int width = crect.width();

	showItemBegin = -1;
	showItemEnd = -1;

	BPoint offset = area.pos();
	int x = area.x();
	int y = area.y();
	for (int i = 0; i < items.size(); i++)
	{
		BListItem* item = items[i];
		BRect rect = item_member(item)->rect + offset;
		if (rect.bottom() >= top)
		{
			showItemBegin = i;
			showItemEnd = i;
			while (++i < items.size())
			{
				showItemEnd = i;
				BListItem* item = items[i];
				if (!item_member(item)->visible)
					continue;
				BRect rect = item_member(item)->rect + offset;
				if (item_member(item)->widget)
					item_member(item)->widget->setRect(rect);
				if (rect.bottom() >= bottom)
					break;
			}
			break;
		}
	}
}
